package com.hzcx.app.simplechat.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.chat.ChatUtil;
import com.hzcx.app.simplechat.ui.friend.adapter.FriendContentAdapter;
import com.hzcx.app.simplechat.ui.friend.bean.FriendCityBean;
import com.hzcx.app.simplechat.ui.home.adapter.HomeSearchMsgAdapter;
import com.hzcx.app.simplechat.ui.user.UserInfoActivity;
import com.hzcx.app.simplechat.util.app.AppHelper;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.log.LogUtils;

import org.litepal.LitePal;
import org.litepal.crud.callback.FindMultiCallback;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 检索消息列表
 */
public class HomeSearchMsgActivity extends BaseActivity {
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.iv_clear)
    ImageView ivClear;
    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.rv_search_msg)
    public RecyclerView rvSearchMsg;
    @BindView(R.id.tv_tips)
    TextView tvTips;
    @BindView(R.id.tv_friend_num)
    TextView tvFriendNum;
    @BindView(R.id.rv_friend)
    RecyclerView rvFriend;
    @BindView(R.id.tv_msg_num)
    TextView tvMsgNum;
    @BindView(R.id.scrollView)
    ScrollView scrollView;

    public List<EMMessage> searchData;
    public HomeSearchMsgAdapter searchMsgAdapter;
    public List<EMConversation> messageData;
    public List<FriendCityBean> friendData;
    public FriendContentAdapter contentAdapter;

    @Override
    public int getLayout() {
        return R.layout.activity_home_search_msg;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {

        // 弹出软键盘
        AppHelper.showSoftKeyboard(etSearch, this);

        friendData = new ArrayList<>();
        contentAdapter = new FriendContentAdapter(friendData);
        rvFriend.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvFriend.setAdapter(contentAdapter);

        configSearchView();

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                searchData.clear();
                searchMsgAdapter.notifyDataSetChanged();
                tvMsgNum.setText("共有" + searchData.size() + "条相关的聊天记录");
                friendData.clear();
                contentAdapter.notifyDataSetChanged();
                tvFriendNum.setText("共有" + friendData.size() + "个相关的联系人");
                if (etSearch.getText().toString().length() > 0) {
                    ivClear.setVisibility(View.VISIBLE);
                    tvTips.setVisibility(View.GONE);

                    // 搜索聊天记录
                    List<EMMessage> list = searchMessage(etSearch.getText().toString());
                    searchData.addAll(list);
                    searchMsgAdapter.setKey(etSearch.getText().toString());
                    searchMsgAdapter.notifyDataSetChanged();
                    tvMsgNum.setText("共有" + searchData.size() + "条相关的聊天记录");

                    // 搜索通讯录
                    searchFriend(etSearch.getText().toString());
                    scrollView.setVisibility(View.VISIBLE);
                } else {
                    ivClear.setVisibility(View.GONE);
                    tvTips.setVisibility(View.VISIBLE);
                    scrollView.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        etSearch.setOnEditorActionListener((textView, i, keyEvent) -> {
            if (i == EditorInfo.IME_ACTION_SEARCH) {
                if (EmptyUtils.isEmpty(etSearch.getText().toString())) {
                    return false;
                }
                searchData.clear();
                searchMsgAdapter.notifyDataSetChanged();
                tvMsgNum.setText("共有" + searchData.size() + "条相关的聊天记录");
                friendData.clear();
                contentAdapter.notifyDataSetChanged();
                tvFriendNum.setText("共有" + friendData.size() + "个相关的联系人");
                if (etSearch.getText().toString().length() > 0) {
                    ivClear.setVisibility(View.VISIBLE);
                    tvTips.setVisibility(View.GONE);
                    // 搜索聊天记录
                    List<EMMessage> list = searchMessage(etSearch.getText().toString());
                    searchData.addAll(list);
                    searchMsgAdapter.setKey(etSearch.getText().toString());
                    searchMsgAdapter.notifyDataSetChanged();

                    // 搜索通讯录
                    searchFriend(etSearch.getText().toString());
                    scrollView.setVisibility(View.VISIBLE);
                } else {
                    ivClear.setVisibility(View.GONE);
                    tvTips.setVisibility(View.VISIBLE);
                }
                return true;
            }
            return false;
        });
    }

    public void configSearchView() {
        searchData = new ArrayList<>();
        searchMsgAdapter = new HomeSearchMsgAdapter(searchData);
        rvSearchMsg.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvSearchMsg.setAdapter(searchMsgAdapter);
    }

    @Override
    public void initData() {
        messageData = new ArrayList<>();
        messageData.addAll(ChatUtil.getInstance().loadConversationList());

        // 联系人列表点击
        try {
            contentAdapter.setOnItemClickListener((adapter, view, position) -> startActivity(new Intent(HomeSearchMsgActivity.this, UserInfoActivity.class)
                    .putExtra(UserInfoActivity.INTENT_USER_ID, friendData.get(position).getMember_id())));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.iv_clear})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_clear:
                etSearch.setText("");
                break;
        }
    }

    /**
     * 搜索聊天记录
     *
     * @param mKeyWords
     * @return
     */
    private List<EMMessage> searchMessage(String mKeyWords) {
        List<EMMessage> msgList = new ArrayList<>();
        for (EMConversation conversation : messageData) {
            List<EMMessage> list = conversation.searchMsgFromDB(mKeyWords, System.currentTimeMillis(), 100, null, EMConversation.EMSearchDirection.UP);
            Iterator<EMMessage> iterator = list.iterator();
            while (iterator.hasNext()) {
                //对搜索结果二次筛选，因为搜索结果群聊中用户的名字包含关键词的也会搜出来，表情符在数据库里存的
                //是英文字符也会被搜出来，所以啊要二次筛选
                EMMessage emMessage = iterator.next();
                if (!((EMTextMessageBody) emMessage.getBody()).getMessage().contains(mKeyWords)) {
                    iterator.remove();
                }
            }
            if (list.size() > 0) {
                msgList.addAll(list);
            }
        }
        return msgList;
    }

    /**
     * 搜索本地用户
     *
     * @param keyWord
     * @return
     */
    private void searchFriend(String keyWord) {
        String sql = "nickname like '%" + keyWord + "%' or remarks_name like '%" + keyWord + "%'";
        LogUtils.d("sql:" + sql);
        LitePal.where(sql).findAsync(FriendCityBean.class).listen(list -> {
            if (list == null || list.size() <= 0) {
                return;
            }
            friendData.addAll(list);
            contentAdapter.notifyDataSetChanged();
            tvFriendNum.setText("共有" + friendData.size() + "个相关的联系人");
        });
    }
}
